import { defineStore } from 'pinia'
import { ref } from 'vue'
import { setItem, getItem, removeItem } from '@/utils'
import api from '@/api'

export default defineStore('auth', () => {
	const token = ref(getItem('TOKEN'))
	const username = ref('')
	const name = ref('')
	const company = ref({
		name: '',
		logo: '',
	})

	const isLogin = () => {
		return !!token.value
	}

	const login = (user) => {
		token.value = user.token
		username.value = user.username
		name.value = user.name
		company.value.name = user.company.name
		company.value.logo = user.company.logo
		setItem('TOKEN', token.value)
	}

	const logout = () => {
		token.value = ''
		username.value = ''
		name.value = ''
		company.value.name = ''
		company.value.logo = ''
		removeItem('TOKEN')
	}

	const getUserInfo = async () => {
		const user = await api.get('/auth/user')
		name.value = user.name
		username.value = user.username
		company.value.name = user.company.name
		company.value.logo = user.company.logo
	}

	const MyInterviewCount = ref(0)
	const MyInterviewTimers = ref(null)
	const getMyInterviewCount = async () => {
		if (!isLogin()) {
			clearMyInterviewTimers()
			return
		}
		const { data } = await api.get('/recruit/myInterviewCount')
		MyInterviewCount.value = data || 0
	}

	const getMyInterviewTimers = async () => {
		if (MyInterviewTimers.value) {
			return
		}
		getMyInterviewCount()
		MyInterviewTimers.value = setInterval(async () => {
			await getMyInterviewCount()
		}, 5000)
	}

  const clearMyInterviewTimers = () => {
    clearInterval(MyInterviewTimers.value)
    MyInterviewTimers.value = null
  }

	return {
		token,
		username,
		name,
		company,

		isLogin,
		login,
		getUserInfo,
		logout,
		MyInterviewCount,
		getMyInterviewTimers,
		getMyInterviewCount,
    clearMyInterviewTimers
	}
})
